package znet

import (
	"fmt"
	"net"
	"tcpChat/conf"
	"tcpChat/ziface"
	"time"
)

type Server struct {
	Name        string             //服务名称
	NetVersion  string             //网络版本
	Ip          string             //
	Port        int                //监听端口
	MsgHandler  ziface.IMsgHandler //执行的业务函数
	ConnManager ziface.IConManager //管理connect连接对象
}

func NewServer() ziface.IServer {
	conf.GlobalObject.Reload()

	return &Server{
		Name:        conf.GlobalObject.Name,
		NetVersion:  "tcp4",
		Ip:          conf.GlobalObject.Host,
		Port:        conf.GlobalObject.Port,
		MsgHandler:  NewMsgHandler(),
		ConnManager: NewConnManager(),
	}
}

//================================ 定义 客户端链接的 handle FUNCTION ===============================//

func CallbackHandleFunction(c *net.TCPConn, bytes []byte, num int) error {
	fmt.Printf("callback function start socket【CONN ID：%d】\n", 0)

	_, err := c.Write(bytes[:num])
	if err != nil {
		fmt.Println("callback function error: ", err.Error())
		return err
	}

	return nil
}

//===============================================================================================//

func (s *Server) Start() {
	fmt.Printf("服务%s 启动： 网络地址【%s:%d】, 网络协议%s\n", s.Name, s.Ip, s.Port, s.NetVersion)

	go func() {

		//启动worker工作池机制
		s.MsgHandler.StartWorkerPool()

		//创建TCP地址
		addr, err := net.ResolveTCPAddr(s.NetVersion, fmt.Sprintf("%s:%d", s.Ip, s.Port))

		if err != nil {
			fmt.Println(err.Error())
			return
		}

		listiner, err := net.ListenTCP(s.NetVersion, addr)

		if err != nil {
			fmt.Println(err.Error())
			return
		}

		fmt.Printf("server %s starting ---------\n", s.Name)

		var cid uint32 = 0
		for {
			conn, err := listiner.AcceptTCP()
			if err != nil {
				fmt.Println(err.Error())
				continue //连接失败，跳过当前连接
			}

			//判断服务器的最大连接数
			if s.ConnManager.Len() >= conf.GlobalObject.MaxConn {
				conn.Close() //关闭连接
				continue
			}

			callConn := NewConnection(s, conn, cid, s.MsgHandler)
			cid++

			//执行网络业务
			go callConn.Start()
		}

	}()
}

func (s *Server) Serve() {
	s.Start()

	for {
		time.Sleep(10 * time.Minute)
	}
}

func (s *Server) Stop() {
	fmt.Printf("服务【%s】停止运行", s.Name)

	s.ConnManager.ClearConn()
}

//添加执行的路由
func (s *Server) AddRouter(msgId uint32, router ziface.IRouter) {
	s.MsgHandler.AddRouter(msgId, router)
}

func (s *Server) GetConnManager() ziface.IConManager {
	return s.ConnManager
}
